package com.iotechn.unimall.admin.myapi.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.core.exception.ThirdPartServiceException;
import com.iotechn.unimall.core.util.GeneratorUtil;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.constant.CacheConst;
import com.iotechn.unimall.data.domain.UserDO;
import com.iotechn.unimall.data.dto.UserDTO;
import com.iotechn.unimall.data.enums.UserLoginType;
import com.iotechn.unimall.data.mapper.mymapper.IStudentMapper;
import com.iotechn.unimall.data.mapper.mymapper.ITeacherMapper;
import com.iotechn.unimall.data.mapper.mymapper.IUserMapper;
import com.iotechn.unimall.data.model.Page;
import com.iotechn.unimall.mydata.domain.Student;
import com.iotechn.unimall.mydata.domain.Teacher;
import com.iotechn.unimall.mydata.domain.User;
import com.iotechn.unimall.mydata.dto.IUser;
import com.iotechn.unimall.mydata.dto.UserAndStudentOrTeacher;
import com.iotechn.unimall.mydata.util.MailUtils;
import okhttp3.Request;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class IUserServiceImpl implements IUserService {

    @Autowired
    private IUserMapper iUserMapper;

    @Autowired
    private ITeacherMapper iTeacherMapper;

    @Autowired
    private IStudentMapper iStudentMapper;

    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private StringRedisTemplate userRedisTemplate;

    @Override
    public String sendVerifyCode(String email) throws Exception {
        String verifyCode = GeneratorUtil.genSixVerifyCode();
        MailUtils.sendMail(email,"线上课程网站邀请你加入","验证码："+verifyCode);
        cacheComponent.putRaw(CacheConst.USER_VERIFY_CODE_PREFIX + email, verifyCode, 300);
        return "ok";
    }

    @Override
    public User register(String email, String password, String name, String nickname, String loginType, String phone, String sno, String school, String department, String major, String garde, String myclass, String degree, String tno, String verifyCode) throws ServiceException {

        checkVerifyCode(email,verifyCode);
        //2.校验用户是否存在
        Integer count = iUserMapper.selectCount(
                new QueryWrapper<User>()
                        .eq("email", email));
        if (count > 0) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_HAS_EXISTED);
        }
        //3.校验成功，注册用户
        User user = new User();
        user.setEmail(email);
        user.setLoginType(Integer.parseInt(loginType));
        user.setName(name);
        user.setNickname(nickname);
        user.setPassword(Md5Crypt.md5Crypt(password.getBytes(), "$1$" + email.substring(0, 5)));
        user.setPhone(phone);

        User name2 = iUserMapper.selectOne(new QueryWrapper<User>().eq("name", user.getName()));
        if(name2!=null){
            throw new AppServiceException(ExceptionDefinition.NAME_ALREADY_EXIST);
        }
        iUserMapper.insertUser(user);
        Integer id = iUserMapper.selectMaxId();
        user.setId(Long.parseLong(id.toString()));
        try {
            if (Integer.parseInt(loginType) == 0) {
                Teacher teacher = new Teacher();
                teacher.setId(Long.parseLong(id.toString()));
                teacher.setTno(tno);
                teacher.setDepartment(department);
                teacher.setSchool(school);
                iTeacherMapper.insertTeacher(teacher);
            }
            if (Integer.parseInt(loginType) == 1) {
                Student student = new Student();
                student.setId(Long.parseLong(id.toString()));
                student.setSno(sno);
                student.setDegree(degree);
                student.setDepartment(department);
                student.setGarde(garde);
                student.setMajor(major);
                student.setMyclass(myclass);
                student.setSchool(school);
                iStudentMapper.insertStudent(student);
            }
        }catch (Exception e){
            iUserMapper.deleteById(id);
            throw new AppServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
        }

        //返回用户信息
        cacheComponent.del(CacheConst.USER_VERIFY_CODE_PREFIX + user.getEmail());
        return user;
    }




    @Override
    public String resetPassword(String email, String password, String verifyCode) throws ServiceException {
        //1.校验验证码
        checkVerifyCode(email, verifyCode);
        //2.校验用户是否存在

        List<User> targetUserList = iUserMapper.selectList(
                new QueryWrapper<User>()
                        .eq("email", email));
        if (CollectionUtils.isEmpty(targetUserList)) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_NOT_EXIST);
        }
        Long id = targetUserList.get(0).getId();
        //3.校验成功，重置密码
        User updateUserDO = new User();
        updateUserDO.setId(id);
        updateUserDO.setPassword(Md5Crypt.md5Crypt(password.getBytes(), "$1$" + email.substring(0, 5)));
        if (iUserMapper.updateById(updateUserDO) > 0) {
            cacheComponent.del(CacheConst.USER_VERIFY_CODE_PREFIX + email);
            return "ok";
        }
        throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
    }

    @Override
    public IUser login(String email, String password) throws ServiceException {
        String cryptPassword = Md5Crypt.md5Crypt(password.getBytes(), "$1$" + email.substring(0, 5));

        IUser login = iUserMapper.login(email, cryptPassword);
        if (login == null) {
            throw new AppServiceException(ExceptionDefinition.USER_PHONE_OR_PASSWORD_NOT_CORRECT);
        }


        String accessToken = GeneratorUtil.genSessionId();
        //放入SESSION专用Redis数据源中
        userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(login));
        login.setAccessToken(accessToken);


        return login;
    }

    @Override
    public UserAndStudentOrTeacher get(Long userId) throws ServiceException {
        User user = iUserMapper.selectById(userId);
        UserAndStudentOrTeacher userAndStudentOrTeacher = new UserAndStudentOrTeacher();
        if (null!=user) {
            if (user.getEmail()!=null){
                userAndStudentOrTeacher.setEmail(user.getEmail());
            }
            if (user.getPassword()!=null){
                userAndStudentOrTeacher.setPassword(user.getPassword());
            }
            if(user.getName()!=null){
                userAndStudentOrTeacher.setName(user.getName());
            }
            if (user.getNickname()!=null){
                userAndStudentOrTeacher.setNickname(user.getNickname());
            }
            if (user.getPhone()!=null){
                userAndStudentOrTeacher.setPhone(user.getPhone());
            }
            if (user.getLoginType()!=null){
                userAndStudentOrTeacher.setLoginType(user.getLoginType());
            }

            if (user.getLoginType()==0){
                Teacher teacher = iTeacherMapper.selectById(userId);
                if (teacher.getTno()!=null){
                    userAndStudentOrTeacher.setTno(teacher.getTno());
                }
                if (teacher.getDepartment()!=null){
                    userAndStudentOrTeacher.setDepartment(teacher.getDepartment());
                }
                if (teacher.getSchool()!=null){
                    userAndStudentOrTeacher.setSchool(teacher.getSchool());
                }
            }
            if (user.getLoginType()==1){
                Student student = iStudentMapper.selectById(userId);
                if (student.getSno()!=null){
                    userAndStudentOrTeacher.setSno(student.getSno());
                }
                if (student.getDegree()!=null){
                    userAndStudentOrTeacher.setDegree(student.getDegree());
                }
                if (student.getDepartment()!=null){
                    userAndStudentOrTeacher.setDepartment(student.getDepartment());
                }
                if (student.getGarde()!=null){
                    userAndStudentOrTeacher.setGarde(student.getGarde());
                }
                if (student.getMyclass()!=null){
                    userAndStudentOrTeacher.setMyclass(student.getMyclass());
                }
                if (student.getMajor()!=null){
                    userAndStudentOrTeacher.setMajor(student.getMajor());
                }
                if (student.getSchool()!=null){
                    userAndStudentOrTeacher.setSchool(student.getSchool());
                }
            }
        }

        return userAndStudentOrTeacher;
    }

    @Override
    public String logout(String accessToken, Long userId) throws ServiceException {
        userRedisTemplate.delete(accessToken);
        return "ok";
    }

    /**
     * 验证码抽取校验
     *
     * @param email
     * @param verifyCode
     * @throws ServiceException
     */
    private void checkVerifyCode(String email, String verifyCode) throws ServiceException {
        String raw = cacheComponent.getRaw(CacheConst.USER_VERIFY_CODE_PREFIX + email);
        if (StringUtils.isEmpty(raw)) {
            throw new AppServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_EXIST);
        }
        if (!raw.equals(verifyCode)) {
            throw new AppServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_CORRECT);
        }
    }
}
